<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    :id="prefixNo"
    style="top:20px;height: 95%;">
    <template slot="footer">
      <a-button v-if="action === 'edit'" @click="toggleScanCheck">
        {{ scanCheckStatus ? $t('button.stopScanCheck') : $t('button.scanCheck') }}
      </a-button>
      <a-input v-if="action === 'edit' && scanCheckStatus"
               :placeholder="$t('placeholder.pleaseScanBarCodeCheck')"
               v-model="scanCheckBarCode"
               @pressEnter="scanCheckPressEnter"
               ref="scanCheckBarCode"
               style="width: 200px; margin-right: 8px;"/>
      <!--      <a-button @click="toPdf">{{ $t('button.downloadCheque') }}</a-button>-->
      <!--      <a-button @click="printInvoice">{{ $t('button.printCheque') }}</a-button>-->
      <a-button @click="handleCancel">{{ $t('button.cancel') }}</a-button>
      <a-button v-if="billPrintFlag" @click="handlePrint('仓库出库')">{{ $t('button.sanlianPrintPreview') }}</a-button>
      <a-button v-if="checkFlag && isCanCheck" :loading="confirmLoading" @click="handleOkAndCheck">
        {{ $t('button.saveAndOut') }}
      </a-button>
      <a-button type="primary" :loading="confirmLoading" @click="handleOk">{{ $t('button.save') }}</a-button>
      <!--发起多级审核-->
      <a-button v-if="!checkFlag" @click="handleWorkflow()" type="primary">{{ $t('button.startProcess') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.customer')" data-step="1"
                         :data-title="$t('search.customer')"
                         :data-intro="$t('intro.customerSelection')">
              <a-select :placeholder="$t('placeholder.pleaseSelectCustomer')"
                        v-decorator="[ 'organId', validatorRules.organId ]"
                        :disabled="!rowCanEdit"
                        :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children"
                        @change="handleOrganChange">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addCustomer">
                    <a-icon type="plus"/>
                    {{ $t('placeholder.addCustomer') }}
                  </div>
                </div>
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billDate')">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billNumber')" data-step="2"
                         :data-title="$t('search.billNumber')"
            >
              <a-input :placeholder="$t('placeholder.pleaseInputBillNumber')" v-decorator.trim="[ 'number' ]" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.linkBill1')" data-step="3"
                         :data-title="$t('search.linkBill1')"
                         :data-intro="$t('intro.linkBill')">
              <a-input-search :placeholder="$t('placeholder.pleaseSelectLinkBill1')" v-decorator="[ 'linkNumber' ]"
                              @search="onSearchLinkNumber"
                              :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal"
                          :ref="refKeys[0]"
                          :loading="materialTable.loading"
                          :columns="materialTable.columns"
                          :dataSource="materialTable.dataSource"
                          :minWidth="minWidth"
                          :maxHeight="300"
                          :rowNumber="false"
                          :rowSelection="rowCanEdit"
                          :actionButton="rowCanEdit"
                          :dragSortAndNumber="rowCanEdit"
                          :highlightRowIndexes="highlightRowIndexes"
                          @valueChange="onValueChange"
                          @added="onAdded"
                          @deleted="onDeleted">
          <template #buttonAfter>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4"
                   :data-title="$t('button.scanEnter')" :data-intro="$t('placeholder.scanEnter')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{ $t('button.scanEnter') }}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 8px 0 12px">
                <a-input :placeholder="$t('placeholder.pleaseScanBarCode')" v-model="scanBarCode"
                         @pressEnter="scanPressEnter"
                         ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px 12px 0 0">
                <a-button @click="stopScan">{{ $t('button.stopScan') }}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;padding-bottom: 5px;">
              <a-col :md="24" :sm="24">
                <a-button style="margin-left: 8px" @click="handleHistoryBillList">
                  <a-icon type="history"/>
                  {{ $t('button.historyBill') }}
                </a-button>
              </a-col>
            </a-row>
            <a-row v-if="rowCanEdit" :gutter="24" style="float:left;padding-bottom: 5px;padding-left:20px;">
              <a-button icon="import" @click="onImport(prefixNo)">{{ $t('button.importDetail') }}</a-button>
            </a-row>
          </template>
          <template #depotBatchSet>
            <a-icon type="down" @click="handleBatchSetDepot" />
          </template>
          <template #depotAdd>
            <a-divider v-if="isTenant" style="margin: 4px 0;" />
            <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @click="addDepot">
              <a-icon type="plus"/>
              {{ $t('button.addDepot') }}
            </div>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="1" :placeholder="$t('placeholder.pleaseInputRemark')" v-decorator="[ 'remark' ]"
                          style="margin-top:8px;" />
            </a-form-item>
          </a-col>

        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <!--税额 %-->
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.taxMoney')"
                         data-step="7"
                         :data-title="$t('search.taxMoney')"
            >
              <a-input v-decorator.trim="[ 'taxMoney' ]" @change="onChangeSaleTaxMoney" suffix="%"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.discount')" data-step="5"
                         :data-title="$t('search.discount')"
                         :data-intro="$t('placeholder.pleaseInputDiscountIntro')">
              <a-input style="width:185px;" :placeholder="$t('placeholder.pleaseInputDiscount')"
                       v-decorator.trim="[ 'discount' ]" suffix="%"
                       @change="onSaleChangeDiscount"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.discountMoney1')"
                         data-step="6"
                         :data-title="$t('search.discountMoney1')"
                         :data-intro="$t('intro.discountMoney')">
              <a-input :placeholder="$t('placeholder.pleaseInputDiscountMoney')"
                       v-decorator.trim="[ 'discountMoney' ]"/>
              <!--              @change="onChangeDiscountMoney"-->
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.discountLastMoney')"
                         data-step="7"
                         :data-title="$t('search.discountLastMoney')"
                         :data-intro="$t('intro.discountLastMoney')">
              <a-input :placeholder="$t('placeholder.pleaseInputDiscountLastMoney')"
                       v-decorator.trim="[ 'discountLastMoney' ]" :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.otherMoney')" data-step="8"
                         :data-title="$t('search.otherMoney')"
                         :data-intro="$t('intro.otherMoney')">
              <a-input :placeholder="$t('placeholder.pleaseInputOtherMoney')" v-decorator.trim="[ 'otherMoney' ]"
                       @change="changeOtherMoney" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.accountName1')" data-step="9"
                         :data-title="$t('search.accountName1')"
                         :data-intro="$t('intro.selectMultipleAccounts')">
              <a-select style="width:185px;" :placeholder="$t('placeholder.pleaseSelectAccount')"
                        v-decorator="[ 'accountId', validatorRules.accountId ]"
                        :dropdownMatchSelectWidth="false" allowClear @select="selectAccount">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addAccount">
                    <a-icon type="plus"/>
                    {{ $t('button.addAccount') }}
                  </div>
                </div>
                <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-tooltip :title="$t('title.manyAccountDetail')">
                <a-button type="default" icon="folder" style="margin-left: 8px;" size="small"
                          v-show="manyAccountBtnStatus" @click="handleManyAccount"/>
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col v-if="depositStatus" :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.deductionDeposit')">
              <a-input v-decorator.trim="[ 'deposit' ]" @change="onChangeDeposit"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.changeAmount2')">
              <a-input :placeholder="$t('placeholder.pleaseInputChangeAmount2')"
                       v-decorator.trim="[ 'changeAmount', validatorRules.changeAmount ]"
                       @change="onChangeChangeAmount"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.debt')" data-step="10"
                         :data-title="$t('search.debt')"
                         :data-intro="$t('intro.debt')">
              <a-input :placeholder="$t('placeholder.pleaseInputDebt')"
                       v-decorator.trim="[ 'debt', validatorRules.price ]"
                       :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.salesMan')" data-step="11"
                         :data-title="$t('search.salesMan')"
                         :data-intro="$t('intro.salesMan')">
              <j-select-multiple style="width:185px;" :placeholder="$t('placeholder.pleaseSelectSalesMan')"
                                 v-model="personList.value"
                                 :options="personList.options"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('search.billAttachment')"
                         data-step="12" :data-title="$t('search.billAttachment')"
                         :data-intro="$t('placeholder.billAttachmentIntro')">
              <j-upload v-model="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <import-item-modal ref="importItemModalForm" @ok="importItemModalFormOk"></import-item-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <history-bill-list ref="historyBillListModalForm"></history-bill-list>
    <workflow-iframe ref="modalWorkflow" @ok="workflowModalFormOk"></workflow-iframe>
    <bill-print-iframe ref="modalPrint"></bill-print-iframe>
    <print-invoice ref="printInvoice" billId="model.id"/>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import ManyAccountModal from '../dialog/ManyAccountModal'
import ImportItemModal from '../dialog/ImportItemModal'
import LinkBillList from '../dialog/LinkBillList'
import CustomerModal from '../../system/modules/CustomerModal'
import DepotModal from '../../system/modules/DepotModal'
import AccountModal from '../../system/modules/AccountModal'
import BatchSetDepot from '../dialog/BatchSetDepot'
import HistoryBillList from '../dialog/HistoryBillList'
import WorkflowIframe from '@/components/tools/WorkflowIframe'
import BillPrintIframe from '../dialog/BillPrintIframe'
import {FormTypes} from '@/utils/JEditableTableUtil'
import {JEditableTableMixin} from '@/mixins/JEditableTableMixin'
import {BillModalMixin} from '../mixins/BillModalMixin'
import {getMpListShort, handleIntroJs} from '@/utils/util'
import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import PrintInvoice from '@/print/PrintInvoice.vue'
import printTemplate from '@/print/printTemplate'
import {hiprint} from 'vue-plugin-hiprint'
import {getAccount, saleOutPrintData} from '@/api/api'
import {getAction} from '@/api/manage'

export default {
  name: 'SaleOutModal',
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    ManyAccountModal,
    ImportItemModal,
    LinkBillList,
    CustomerModal,
    DepotModal,
    AccountModal,
    BatchSetDepot,
    HistoryBillList,
    WorkflowIframe,
    BillPrintIframe,
    JUpload,
    JDate,
    JSelectMultiple,
    PrintInvoice,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes
    }
  },
  data() {
    return {
      title: this.$t('dynamic.operation'),
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      operTimeStr: '',
      prefixNo: 'DU',
      depositStatus: false,
      fileList: [],
      rowCanEdit: true,
      model: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 8}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      refKeys: ['materialDataTable'],
      activeKey: 'materialDataTable',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: this.$t('search.depotName'),
            key: 'depotId',
            width: '8%',
            type: FormTypes.select,
            placeholder: '请选择${title}',
            options: [],
            allowSearch: true,
            validateRules: [{required: true, message: '${title}不能为空'}]
          },
          {
            title: this.$t('search.barCode'),
            key: 'barCode',
            width: '12%',
            type: FormTypes.popupJsh,
            kind: 'material',
            multi: true,
            validateRules: [{required: true, message: '${title}不能为空'}]
          },
          {title: this.$t('search.name'), key: 'name', width: '9%', type: FormTypes.normal},
          {title: this.$t('search.standard'), key: 'standard', width: '7%', type: FormTypes.normal},
          {title: this.$t('search.model'), key: 'model', width: '7%', type: FormTypes.normal},
          { title: this.$t('search.color'), key: 'color', width: '5%', type: FormTypes.normal },
          { title: this.$t('search.materialOther'), key: 'materialOther', width: '5%', type: FormTypes.normal },
          { title: this.$t('search.stock'), key: 'stock', width: '5%', type: FormTypes.normal },
          { title: this.$t('search.unit'), key: 'unit', width: '4%', type: FormTypes.normal },
          {
            title: this.$t('search.snList'),
            key: 'snList',
            width: '10%',
            type: FormTypes.popupJsh,
            kind: 'sn',
            multi: true
          },
          {
            title: this.$t('search.batchNumber'),
            key: 'batchNumber',
            width: '7%',
            type: FormTypes.popupJsh,
            kind: 'batch',
            multi: false
          },
          {
            title: this.$t('search.expirationDate'),
            key: 'expirationDate',
            width: '6%',
            type: FormTypes.input,
            readonly: true
          },
          {title: this.$t('search.sku'), key: 'sku', width: '8%', type: FormTypes.normal},
          { title: this.$t('search.preNumber'), key: 'preNumber', width: '4%', type: FormTypes.normal },
          { title: this.$t('search.finishNumber2'), key: 'finishNumber', width: '4%', type: FormTypes.normal },
          {
            title: this.$t('search.quantity'),
            key: 'operNumber',
            width: '5%',
            type: FormTypes.inputNumber,
            statistics: true,
            validateRules: [{required: true, message: '${title}不能为空'}]
          },
          { title: this.$t('search.unitPrice'), key: 'unitPrice', width: '4%', type: FormTypes.inputNumber },
          {
            title: this.$t('search.allPrice'),
            key: 'allPrice',
            width: '10%',
            type: FormTypes.inputNumber,
            statistics: true
          },
          // {
          //   title: this.$t('search.taxRate1'),
          //   key: 'taxRate',
          //   width: '4%',
          //   type: FormTypes.inputNumber,
          //   placeholder: '%'
          // },
          // {
          //   title: this.$t('search.taxMoney'),
          //   key: 'taxMoney',
          //   width: '5%',
          //   type: FormTypes.inputNumber,
          //   readonly: true,
          //   statistics: true
          // },
          // {
          //   title: this.$t('search.taxLastMoney'),
          //   key: 'taxLastMoney',
          //   width: '8%',
          //   type: FormTypes.inputNumber,
          //   statistics: true
          // },
          {
            title: this.$t('search.discount'),
            key: 'discount',
            width: '4%',
            type: FormTypes.inputNumber,
            placeholder: '%'
          },
          {
            title: this.$t('search.afterDiscount'),
            key: 'discountMoney',
            width: '6%',
            type: FormTypes.inputNumber,
          },
          { title: this.$t('search.remark'), key: 'remark', width: '6%', type: FormTypes.input },
          { title: this.$t('search.linkId'), key: 'linkId', width: '5%', type: FormTypes.hidden }
        ]
      },
      confirmLoading: false,
      validatorRules: {
        operTime: {
          rules: [
            { required: true, message: this.$t('placeholder.pleaseInputBillDate') }
          ]
        },
        organId: {
          rules: [
            { required: true, message: this.$t('message.pleaseSelectCustomer') }
          ]
        },
        accountId: {
          rules: [
            { required: true, message: this.$t('placeholder.pleaseSelectSettleAccount') }
          ]
        },
        changeAmount: {
          rules: [
            { required: true, message: this.$t('message.pleaseInputChangeAmountIfEmpty') },
            {
              pattern: /^(([0-9][0-9]*)|([0]\.\d{0,4}|[0-9][0-9]*\.\d{0,4}))$/,
              message: this.$t('message.amountFormatIsIncorrect')
            }
          ]
        }
      },
      url: {
        add: '/depotHead/addDepotHeadAndDetail',
        edit: '/depotHead/updateDepotHeadAndDetail',
        detailList: '/depotItem/getDetailList'
      },
      printPreviewVisible: false,
      hiprintTemplate: null,
      scanCheckStatus: false,
      scanCheckBarCode: '',
      highlightRowIndexes: []
    }
  },

  mounted() {
    this.buildDesigner()
  },

  methods: {
    buildDesigner() {
      // 确保 hiprint 库已经加载
      if (typeof hiprint !== 'undefined') {
        $('#hiprint-printTemplate').empty() // 先清空, 避免重复构建
        this.hiprintTemplate = new hiprint.PrintTemplate({
          template: printTemplate,
          settingContainer: '#PrintElementOptionSetting' // 元素参数容器
        })
      }
    },
    addBefore() {
      //this.materialTable.dataSource = []

    },
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      // console.log('saleOutSignModal', this.model)
      // console.log('modal.list', this.materialTable.dataSource)
      this.billStatus = '0'
      this.currentSelectDepotId = ''
      this.rowCanEdit = true
      this.materialTable.columns[1].type = FormTypes.popupJsh
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'snList', 0)
      this.changeFormTypes(this.materialTable.columns, 'batchNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'expirationDate', 0)
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 0)
      if (this.action === 'add') {
        this.depositStatus = false
        this.addInit('DU')
        this.personList.value = ''
        this.fileList = []
        this.$nextTick(() => {
          handleIntroJs(this.prefixNo, 1)
        })

      } else {
        if (this.model.linkNumber) {
          this.rowCanEdit = false
          this.materialTable.columns[1].type = FormTypes.normal
        }
        this.model.operTime = this.model.operTimeStr
        if (this.model.deposit) {
          this.depositStatus = true
        } else {
          this.depositStatus = false
          this.model.deposit = 0
        }
        this.model.debt = (this.model.discountLastMoney + this.model.otherMoney - this.model.deposit - this.model.changeAmount).toFixed(2)
        if (this.model.accountId == null) {
          this.model.accountId = 0
          this.manyAccountBtnStatus = true
          this.accountIdList = this.model.accountIdList
          this.accountMoneyList = this.model.accountMoneyList
        } else {
          this.manyAccountBtnStatus = false
        }
        this.personList.value = this.model.salesMan
        this.fileList = this.model.fileName
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'operTime', 'number', 'linkNumber', 'remark', 'taxMoney',
            'discount', 'discountMoney', 'discountLastMoney', 'otherMoney', 'accountId', 'deposit', 'changeAmount', 'debt', 'salesMan'))
        })
        // 加载子表数据
        let params = {
          headerId: this.model.id,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList')),  //扩展属性
          linkType: 'basic'
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList
        this.requestSubTableData(url, params, this.materialTable)
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initSystemConfig()
      this.initCustomer(0)
      this.initSalesman()
      this.initDepot()
      this.initAccount(0)
      this.initPlatform()
    },
    addInit(amountNum) {
      getAction('/sequence/buildSaleOutNumber').then((res) => {
        if (res && res.code === 200) {
          this.model.defaultNumber = amountNum + res.data.defaultNumber
          this.form.setFieldsValue({'number': amountNum + res.data.defaultNumber})
        }
      })
      this.$nextTick(() => {
        this.form.setFieldsValue({
          'operTime': getNowFormatDateTime(), 'discount': 0,
          'discountMoney': 0, 'discountLastMoney': 0, 'otherMoney': 0, 'changeAmount': 0, 'debt': 0
        })
      })
      this.$nextTick(() => {
        getAccount({}).then((res) => {
          if (res && res.code === 200) {
            for (const item of res.data.accountList) {
              if (item.isDefault) {
                this.form.setFieldsValue({'accountId': item.id})
              }
            }
          }
        })
      })
      this.accountIdList = []
      this.accountMoneyList = []
      this.manyAccountBtnStatus = false
    },
    printInvoice() {
      if (!this.hiprintTemplate) {
        console.error('HiPrint template is not initialized')
        return
      }
      let printParam = {
        id: this.model.id
      }
      let data = null
      this.confirmLoading = true // 开始加载
      saleOutPrintData(printParam).then((res) => {
        if (res && res.code === 200) {
          data = res.data
          //this.hiprintTemplate.toPdf(data)
          this.hiprintTemplate.print(data, {
            styleHandler: () => {
              return `
                  table, th, td {
                  border: 1px solid black;
                  border-collapse: collapse;
                }
              `
            }
          })
        } else {
          this.$message.error('get print data failed')
        }
      }).catch((error) => {
        console.error('获取打印数据出错:', error)
        this.$message.error('获取打印数据出错')
      }).finally(() => {
        this.confirmLoading = false // 结束加载
      })

      //this.$refs.printInvoice.show();

    },
    toPdf () {
      if (!this.hiprintTemplate) {
        console.error('HiPrint template is not initialized')
        return
      }
      let printParam = {
        id: this.model.id
      }
      let data = null
      this.confirmLoading = true // 开始加载
      saleOutPrintData(printParam).then((res) => {
        if (res && res.code === 200) {
          data = res.data
          this.hiprintTemplate.toPdf(data, 'Invoice')
          // this.hiprintTemplate.print(data, {
          //   styleHandler: () => {
          //     return `
          //         table, th, td {
          //         border: 1px solid black;
          //         border-collapse: collapse;
          //       }
          //     `
          //   }
          // })
        } else {
          this.$message.error('get print data failed')
        }
      }).catch((error) => {
        console.error('获取打印数据出错:', error)
        this.$message.error('获取打印数据出错')
      }).finally(() => {
        this.confirmLoading = false // 结束加载
      })
    },
    handleHistoryBillList() {
      let organId = this.form.getFieldValue('organId')
      this.$refs.historyBillListModalForm.show('出库', '销售', '客户', organId)
      this.$refs.historyBillListModalForm.disableSubmit = false
    },
    onSearchLinkNumber() {
      this.$refs.linkBillList.show('其它', '销售订单', '客户', '1,3')
      this.$refs.linkBillList.title = this.$t('title.selectSalesOrder')
    },
    linkBillListOk(selectBillDetailRows, linkNumber, organId, discountMoney, deposit, remark, depotId) {
      let that = this
      this.rowCanEdit = false
      this.materialTable.columns[1].type = FormTypes.normal
      this.changeFormTypes(this.materialTable.columns, 'preNumber', 1)
      this.changeFormTypes(this.materialTable.columns, 'finishNumber', 1)
      if (selectBillDetailRows && selectBillDetailRows.length > 0) {
        let listEx = []
        let allTaxLastMoney = 0
        for (let j = 0; j < selectBillDetailRows.length; j++) {
          let info = selectBillDetailRows[j]
          if (info.finishNumber > 0) {
            info.operNumber = info.preNumber - info.finishNumber
            //info.operNumber = info.preNumber
            info.allPrice = info.operNumber * info.unitPrice - 0
            let taxRate = info.taxRate - 0
            info.taxMoney = (info.allPrice * taxRate / 100).toFixed(2) - 0
            info.taxLastMoney = (info.allPrice + info.taxMoney).toFixed(2) - 0
          }
          info.linkId = info.id
          allTaxLastMoney += info.taxLastMoney
          listEx.push(info)
          this.changeColumnShow(info)
        }
        this.materialTable.dataSource = listEx
        ///给优惠后金额重新赋值
        allTaxLastMoney = allTaxLastMoney ? allTaxLastMoney : 0
        let discount = 0
        if (allTaxLastMoney !== 0) {
          discount = (discountMoney / allTaxLastMoney * 100).toFixed(2) - 0
        }
        let discountLastMoney = (allTaxLastMoney - discountMoney).toFixed(2) - 0
        //出库单默认不收款
        let debt = discountLastMoney
        if (deposit) {
          this.depositStatus = true
          debt = (discountLastMoney - deposit).toFixed(2) - 0
        }
        let changeAmount = discountLastMoney - debt
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'organId': organId,
            'linkNumber': linkNumber,
            'discount': discount,
            'discountMoney': discountMoney,
            'discountLastMoney': discountLastMoney,
            'deposit': deposit,
            'changeAmount': changeAmount,
            'debt': debt,
            'remark': remark
          })
        })
        //判断后进行仓库的切换
        if (depotId) {
          setTimeout(function () {
            that.batchSetDepotModalFormOk(depotId)
          }, 1000)
        }
      }
    },
    //其它费用
    changeOtherMoney(e) {
      const value = e.target.value - 0
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let deposit = this.form.getFieldValue('deposit')
      let debt = (discountLastMoney + value).toFixed(2) - 0
      if (deposit) {
        debt = (debt - deposit).toFixed(2) - 0
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({'changeAmount': 0, 'debt': debt})
      })
    },
    //提交单据时整理成formData，点击保存
    classifyIntoFormData(allValues) {
      let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values

      billMain.type = '出库'
      billMain.subType = '销售'
      for (let item of detailArr) {
        totalPrice += item.allPrice - 0
      }
      billMain.totalPrice = totalPrice
      if (billMain.accountId === 0) {
        billMain.accountId = ''
      }
      billMain.accountIdList = this.accountIdList.length > 0 ? JSON.stringify(this.accountIdList) : ''
      billMain.accountMoneyList = this.accountMoneyList.length > 0 ? JSON.stringify(this.accountMoneyList) : ''
      if (this.fileList && this.fileList.length > 0) {
        billMain.fileName = this.fileList
      } else {
        billMain.fileName = ''
      }
      if (this.model.id) {
        billMain.id = this.model.id
      }
      billMain.salesMan = this.personList.value
      billMain.status = this.billStatus
      return {
        info: JSON.stringify(billMain),
        rows: JSON.stringify(detailArr)
      }
    },
    toggleScanCheck() {
      this.scanCheckStatus = !this.scanCheckStatus
      if (this.scanCheckStatus) {
        this.$nextTick(() => {
          this.$refs.scanCheckBarCode.focus()
        })
      }
      // 点击停止扫码检查时重置高亮
      if (!this.scanCheckStatus) {
        this.resetHighlight()
      }
    },

    scanCheckPressEnter() {
      const barCode = this.scanCheckBarCode
      const found = this.materialTable.dataSource.find(item => item.barCode === barCode)

      if (found) {
        // 找到条码,添加到高亮行索引数组中
        const index = this.materialTable.dataSource.indexOf(found)
        if (!this.highlightRowIndexes.includes(index)) {
          this.highlightRowIndexes.push(index)
        }
      } else {
        this.$message.warning(this.$t('message.barcodeNotFound'))
      }

      this.scanCheckBarCode = ''
    },

    // 重置高亮方法
    resetHighlight() {
      this.highlightRowIndexes = []
    },

    // 修改关闭窗口方法
    handleCancel() {
      this.resetHighlight()
      this.close()
      this.materialTable.dataSource = []
    },

    // 修改关闭方法
    close() {
      this.$emit('close')
      this.visible = false
      this.scanCheckStatus = false // 确保扫码检查状态也被重置
      this.materialTable.dataSource = []
    },

  }
}
</script>
<style scoped>
.ant-table-row.highlight {
  background-color: #e6f7ff;
}

/* 修改高亮行的背景色为橙色 */
:deep(.tr-highlight) {
  background-color: #ffd591 !important; /* 使用橙色 */
}
</style>